let fs = require('fs');

function calculateBbox(coordinates) {
  let minX = Infinity, minY = Infinity;
  let maxX = -Infinity, maxY = -Infinity;
  coordinates.forEach(coord => {
    let x = coord[0]; // 经度
    let y = coord[1]; // 纬度
    minX = Math.min(minX, x);
    minY = Math.min(minY, y);
    maxX = Math.max(maxX, x);
    maxY = Math.max(maxY, y);
  });
  return [minX, minY, maxX, maxY];
}

async function ensureDirExists(dirPath) {
  try {
    fs.mkdirSync(dirPath, { recursive: true });
    console.log(`目录已创建或已存在: ${dirPath}`);
  } catch (err) {
    if (err.code !== 'EEXIST') {
      console.error(`创建目录失败: ${dirPath}`, err);
      throw err;
    }
  }
}

async function writejsonSync() {
  let id = 1;
  let jsonpath = 'D:\\GongZuoKongJian\\one_map-jn\\文档内容\\济南红色围栏.json';
  let data = fs.readFileSync(jsonpath);
  let jsondata = JSON.parse(data.toString());
  let arr = [];
  // 使用 for...of 循环代替 forEach，以便正确处理 await
  for (let county of Object.keys(jsondata)) {
    let jsonItem = jsondata[county];
    for (let item of jsonItem) {
      let dirName = `./20250618/${item.pinyin}`;
      await ensureDirExists(dirName); // 确保目录存在
      let coordinates = item.code;
      if (typeof coordinates == 'string') coordinates = JSON.parse(coordinates);
      let json = {
        'type': 'FeatureCollection',
        'features': [
          {
            'type': 'Feature',
            'id': id,
            'properties': {
              '_draw_type': 'fill',
            },
            'geometry': {
              'type': 'Polygon',
              'coordinates': [coordinates],
            },
            'bbox': calculateBbox(coordinates),
          },
        ],
      };
      try {
        // 同步写入文件
        fs.writeFileSync(`${dirName}/${item.namePinyin}.json`, JSON.stringify(json), 'utf8');
        console.log(`文件 ${item.name}.json 同步写入成功`);

        // 修正路径格式，移除前面的 ./
        let cleanDirName = dirName.replace('./', '');
        arr.push(`import ${item.namePinyin} from '@/assets/geoJson/fdl-control/${cleanDirName}/${item.namePinyin}.json';`);
        id++;
      } catch (err) {
        console.error(`写入文件 ${item.name}.json 时出错:`, err);
      }
    }
  }
  // 写入导入语句到文件
  try {
    fs.writeFileSync('./imports.js', arr.join('\n'), 'utf8');
    console.log(`成功生成 ${arr.length} 条导入语句到 imports.js`);
  } catch (err) {
    console.error('写入导入语句文件时出错:', err);
  }
  return arr; // 返回导入语句数组
}

writejsonSync().then(imports => {
  console.log(JSON.stringify(imports));
});

